<template>
  <div class="event-list-container">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="赛事名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入赛事名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="赛事状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="筹备中" value="preparing" />
            <el-option label="报名中" value="registration" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已结束" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="运动类型">
          <el-select
            v-model="searchForm.sportType"
            placeholder="请选择运动类型"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="篮球" value="basketball" />
            <el-option label="羽毛球" value="badminton" />
            <el-option label="足球" value="football" />
            <el-option label="网球" value="tennis" />
            <el-option label="乒乓球" value="pingpong" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleCreate">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            创建赛事
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedEvents.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
          <el-button @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出数据
          </el-button>
        </div>

        <div class="action-right">
          <el-button circle @click="handleRefresh">
            <IconifyIconOffline icon="ep:refresh" />
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 赛事列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="eventList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="赛事封面" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.cover"
              :alt="row.name"
              class="event-cover"
              fit="cover"
              :preview-src-list="[row.cover]"
            />
          </template>
        </el-table-column>

        <el-table-column prop="name" label="赛事名称" min-width="200">
          <template #default="{ row }">
            <div class="event-name">
              <div class="name">{{ row.name }}</div>
              <div class="subtitle">{{ row.subtitle }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="sportType" label="运动类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getSportTypeColor(row.sportType)">
              {{ getSportTypeName(row.sportType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="参赛队伍" width="100">
          <template #default="{ row }">
            <span>{{ row.currentTeams }}/{{ row.maxTeams }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="registrationFee" label="报名费" width="100">
          <template #default="{ row }">
            <span v-if="row.registrationFee === 0" class="free-tag">免费</span>
            <span v-else class="fee-tag">¥{{ row.registrationFee }}</span>
          </template>
        </el-table-column>

        <el-table-column label="赛事时间" width="180">
          <template #default="{ row }">
            <div class="time-info">
              <div>{{ formatDate(row.startDate) }}</div>
              <div class="time-sub">至 {{ formatDate(row.endDate) }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="organizer" label="主办方" width="120" />

        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleSchedule(row)"
            >
              赛程
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: "",
  status: "",
  sportType: "",
  dateRange: []
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 状态
const loading = ref(false);
const selectedEvents = ref([]);

// 赛事列表数据
const eventList = ref([
  {
    id: 1,
    name: "2024年春季羽毛球锦标赛",
    subtitle: "全市业余羽毛球爱好者的盛会",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=badminton%20tournament%20poster%2C%20professional%20sports%20event%2C%20championship%20design&image_size=portrait_4_3",
    sportType: "badminton",
    status: "registration",
    currentTeams: 24,
    maxTeams: 32,
    registrationFee: 200,
    startDate: "2024-03-15",
    endDate: "2024-03-17",
    organizer: "市体育局",
    createTime: "2024-01-15 10:00:00"
  },
  {
    id: 2,
    name: "青少年篮球联赛",
    subtitle: "培养青少年篮球人才",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=youth%20basketball%20tournament%2C%20energetic%20young%20players%2C%20sports%20competition&image_size=portrait_4_3",
    sportType: "basketball",
    status: "ongoing",
    currentTeams: 16,
    maxTeams: 16,
    registrationFee: 0,
    startDate: "2024-02-01",
    endDate: "2024-02-28",
    organizer: "青少年体育协会",
    createTime: "2024-01-10 14:30:00"
  },
  {
    id: 3,
    name: "企业足球友谊赛",
    subtitle: "促进企业间体育交流",
    cover:
      "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=corporate%20football%20match%2C%20business%20teams%20playing%2C%20friendly%20competition&image_size=portrait_4_3",
    sportType: "football",
    status: "completed",
    currentTeams: 8,
    maxTeams: 8,
    registrationFee: 500,
    startDate: "2024-01-20",
    endDate: "2024-01-21",
    organizer: "企业体育联盟",
    createTime: "2024-01-05 09:15:00"
  }
]);

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format("MM-DD");
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 获取运动类型名称
const getSportTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    basketball: "篮球",
    badminton: "羽毛球",
    football: "足球",
    tennis: "网球",
    pingpong: "乒乓球"
  };
  return typeMap[type] || type;
};

// 获取运动类型颜色
const getSportTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    basketball: "warning",
    badminton: "success",
    football: "primary",
    tennis: "info",
    pingpong: "danger"
  };
  return colorMap[type] || "";
};

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    preparing: "info",
    registration: "warning",
    ongoing: "primary",
    completed: "success",
    cancelled: "danger"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    preparing: "筹备中",
    registration: "报名中",
    ongoing: "进行中",
    completed: "已结束",
    cancelled: "已取消"
  };
  return statusMap[status] || "未知";
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadEventList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    status: "",
    sportType: "",
    dateRange: []
  });
  pagination.page = 1;
  loadEventList();
};

// 创建赛事
const handleCreate = () => {
  router.push("/event/create");
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedEvents.value.length} 个赛事吗？`,
      "批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用批量删除API
    ElMessage.success("删除成功");
    loadEventList();
  } catch {
    // 用户取消
  }
};

// 导出数据
const handleExport = () => {
  // 这里应该调用导出API
  ElMessage.success("导出成功");
};

// 刷新
const handleRefresh = () => {
  loadEventList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedEvents.value = selection;
};

// 查看赛事
const handleView = (row: any) => {
  router.push(`/event/detail/${row.id}`);
};

// 编辑赛事
const handleEdit = (row: any) => {
  router.push(`/event/edit/${row.id}`);
};

// 赛程管理
const handleSchedule = (row: any) => {
  router.push(`/event/schedule/${row.id}`);
};

// 删除赛事
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除赛事 "${row.name}" 吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用删除API
    ElMessage.success("删除成功");
    loadEventList();
  } catch {
    // 用户取消
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.page = 1;
  loadEventList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadEventList();
};

// 加载赛事列表
const loadEventList = async () => {
  loading.value = true;
  try {
    // 这里应该调用API获取赛事列表
    await new Promise(resolve => setTimeout(resolve, 500));

    // 模拟分页数据
    pagination.total = 50;

    console.log("搜索条件:", searchForm);
    console.log("分页信息:", pagination);
  } catch (error) {
    ElMessage.error("加载赛事列表失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadEventList();
});
</script>

<style scoped lang="scss">
.event-list-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.search-form {
  .el-form-item {
    margin-bottom: 0;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left {
    display: flex;
    gap: 8px;
  }
}

.event-cover {
  width: 80px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
}

.event-name {
  .name {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }

  .subtitle {
    font-size: 12px;
    color: #909399;
  }
}

.time-info {
  .time-sub {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }
}

.free-tag {
  color: #67c23a;
  font-weight: 600;
}

.fee-tag {
  color: #e6a23c;
  font-weight: 600;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .event-list-container {
    padding: 10px;
  }

  .search-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 16px;
    }
  }

  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;

    .action-left {
      justify-content: center;
      flex-wrap: wrap;
    }

    .action-right {
      align-self: center;
    }
  }

  .event-cover {
    width: 60px;
    height: 45px;
  }
}
</style>